'''
Created on Dec 9, 2010

@author: german
'''

from django.contrib.auth.models import User
from django.core.paginator import Paginator, EmptyPage, InvalidPage

def can_do(user, perm, owner):
    if is_same_user(user, owner) or has_perm(user, perm):
        return True
    return False 

def is_same_user(userid, user):
    if isinstance(userid, type('')):
        return userid == user.username
    if isinstance(userid, User):
        return userid.pk == user.pk
    return False

def has_perm(user, perm=None, true=False):
    if true: return True
    return has_perm_simple(user, perm)

def has_perm_simple(user, perm=None):
    if isinstance(perm, tuple):
        perm, true = perm
        if true: return True 
    if perm is not None and user.is_authenticated():
        return user.has_perm(perm)
    return False

def send_message(text="OK", request=None):
    request.user.message_set.create(message=text)
    
def get_page(q, page=1, limit = 30):
    paginator = Paginator(q, limit)

    try:
        page = int(page)
    except ValueError:
        page = 1

    try:
        lst = paginator.page(page)
    except (EmptyPage, InvalidPage):
        lst = paginator.page(paginator.num_pages)
    return lst    